# -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
from core.models import Mailbox
from core.views import _fetch_recent_emails

class Command(BaseCommand):
    help = "Fetch recent emails for given mailbox id(s) without processing."

    def add_arguments(self, parser):
        parser.add_argument('--mailbox', type=int, help='Mailbox ID to fetch. If omitted, fetch for all enabled mailboxes.')
        parser.add_argument('--limit', type=int, default=50, help='Max emails per mailbox to fetch (1-200). Default 50')

    def handle(self, *args, **options):
        limit = options.get('limit') or 50
        limit = max(1, min(int(limit), 200))
        mailbox_id = options.get('mailbox')
        mailboxes = []
        if mailbox_id:
            try:
                mailboxes = [Mailbox.objects.get(pk=mailbox_id)]
            except Mailbox.DoesNotExist:
                raise CommandError(f"Mailbox {mailbox_id} does not exist")
        else:
            mailboxes = list(Mailbox.objects.filter(enabled=True))
        total_fetched = 0
        total_skipped = 0
        created_total = 0
        for mb in mailboxes:
            stats = _fetch_recent_emails(mb, limit=limit)
            total_fetched += stats.get('fetched', 0)
            total_skipped += stats.get('skipped', 0)
            created_total += len(stats.get('created_ids', []))
            self.stdout.write(self.style.SUCCESS(f"Mailbox {mb.id} '{mb.name}': fetched={stats['fetched']} skipped={stats['skipped']}"))
        self.stdout.write(self.style.SUCCESS(f"All done. fetched={total_fetched} skipped={total_skipped} created={created_total}"))